package com.boot.ys.mybatisplus.Test;

import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

public class AboJavaFileRename {


    public static void main(String[] args) throws Exception {

        // 项目根目录
        String PROJECT_ROOT = "C:\\Users\\Acer\\Desktop\\1\\springboot6b9p2i50\\src";// 33333333333333333333333333333333333333333


        HashMap<String, String> replacementMap = new HashMap<>();
        // key abo原来的拼音全小写无下划线   value：英文表名带下划线-全小写
        replacementMap.put("lajifenlei", "garbage_classification");     // 垃圾分类
        replacementMap.put("jifenshangpin", "points_based_goods");     // 积分商品
        replacementMap.put("lajishibie", "garbage_identification");     // 垃圾识别
        replacementMap.put("yonghu", "user_info");     // 用户
        replacementMap.put("jifenduihuan", "points_redemption");     // 积分兑换


        for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
            editFileName(entry.getKey(), entry.getValue(), PROJECT_ROOT);
        }

        // 直接生成重命名语句
        System.out.println("---------------------------------------- MySQL表名直接更新语句开始---------------------------------------- ");
        System.out.println("生成语句如下-- 生成时间: " + java.time.LocalDateTime.now());
        System.out.println();
        for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
            System.out.printf("RENAME TABLE %s TO %s;\n", entry.getKey(), entry.getValue());
        }

        System.out.println();
        // System.out.println("-- 验证语句");
        // for (String englishName : replacementMap.values()) {
        //     System.out.printf("SHOW TABLES LIKE '%s';\n", englishName);
        // }

        System.out.println("---------------------------------------- MySQL表名直接更新语句结束---------------------------------------- ");


        System.out.println("---------------------------------------- Java类更新脚本开始---------------------------------------- ");
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
            sb.append("if (\"")
                    .append(entry.getKey())
                    .append("\".equals(tableName)) {\n")
                    .append("\ttableName = \"")
                    .append(entry.getValue())
                    .append("\";\n")
                    .append("}\n\n");
        }
        System.out.println(sb.toString().trim());
        System.out.println("---------------------------------------- Java类更新脚本结束---------------------------------------------- ");


    }


    static void editFileName(String oldTableName, String newTableName, String PROJECT_ROOT) throws IOException {


        // 下划线，转换为驼峰命名首字母大写 hot_spot_info =》 HotSpotInfo
        String newClassName = toCamelCase(newTableName);

        // 原来的类名拼音-首字母需要大写后面的字母不需要大写-就是没改之前的他们的类名
        String oldClassName = oldTableName.substring(0, 1).toUpperCase() + oldTableName.substring(1);

        Map<String, String> map = new HashMap<>();
        // 更新Java类名称
        map.put(oldClassName + "Controller", newClassName + "Controller");
        map.put(oldClassName + "Service", newClassName + "Service");
        map.put(oldClassName + "ServiceImpl", newClassName + "ServiceImpl");
        map.put(oldClassName + "Dao", newClassName + "Dao");
        map.put(oldClassName + "Entity", newClassName + "Entity");
        map.put(oldClassName + "VO", newClassName + "VO");
        map.put(oldClassName + "View", newClassName + "View");


        // 去除Service注解上的别名
        map.put("@Service(\"" + oldTableName + "Service\")", "@Service");


        // 更新实体类上面的表名称
        map.put("@TableName(\"" + oldTableName + "\")", "@TableName(\"" + newTableName + "\")");

        // 更新service类例如：yonghuService

        // 分割首字符与剩余部分
        String firstChar = newClassName.substring(0, 1).toLowerCase(); // 首字母转小写
        String remaining = newClassName.substring(1); // 保留剩余部分
        String resultTableName = firstChar + remaining;

        map.put(oldTableName + "Service", resultTableName + "Service");

        // 处理Controller类里面的请求路径@RequestMapping("/bumenxinxi")
        //！！！！！！！！！！！！！如果不改前端页面的请求路径，这里的这个代码可以注释掉！
        map.put("@RequestMapping(\"/" + oldTableName + "\")", "@RequestMapping(\"/" + resultTableName + "\")");


        Path startPath = Paths.get(PROJECT_ROOT);

        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 处理文件名
                String fileName = file.getFileName().toString();
                if (shouldProcessFile(fileName)) {
                    // 重命名文件
                    String newFileName = replaceAll(fileName, map);
                    if (!newFileName.equals(fileName)) {
                        Path newFile = file.resolveSibling(newFileName);
                        System.out.println("原来的: " + file + "改为新的 -> " + newFile);
                        Files.move(file, newFile, StandardCopyOption.REPLACE_EXISTING);
                        file = newFile; // 更新引用为新文件
                    }

                    // 处理文件内容
                    processFileContent(file, map);
                }
                return FileVisitResult.CONTINUE;
            }
        });

        System.out.println("更新Java类完毕");

        RenameXml.updateXmlContent(PROJECT_ROOT, oldTableName, newTableName);

    }

    private static boolean shouldProcessFile(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex < 0) return false;
        String ext = fileName.substring(dotIndex + 1).toLowerCase();

        // 包含的文件扩展名
        Set<String> set = new HashSet<>();
        set.add("java");
        set.add("xml");
        return set.contains(ext);
    }

    private static String replaceAll(String input, Map<String, String> map) {

        String result = input;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            result = result.replace(entry.getKey(), entry.getValue());
        }
        return result;
    }

    private static void processFileContent(Path file, Map<String, String> map) throws IOException {
        String content = new String(Files.readAllBytes(file), "UTF-8");

        String result = content;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            result = result.replace(entry.getKey(), entry.getValue());
        }


        if (!result.equals(content)) {
            System.out.println("Updating content of: " + file);
            Files.write(file, result.getBytes("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING);
        }
    }


    /**
     * 将字符串转换为驼峰式（PascalCase）
     * - 如果包含下划线，按 snake_case 转 PascalCase（如 "hot_spot" → "HotSpot"）
     * - 如果不包含下划线，直接首字母大写（如 "spot" → "Spot"）
     */
    public static String toCamelCase(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }

        // 如果包含下划线，按 snake_case 处理
        if (input.contains("_")) {
            String[] parts = input.split("_");
            StringBuilder result = new StringBuilder();

            for (String part : parts) {
                if (!part.isEmpty()) {
                    // 每个单词首字母大写
                    result.append(Character.toUpperCase(part.charAt(0)));
                    if (part.length() > 1) {
                        result.append(part.substring(1).toLowerCase());
                    }
                }
            }
            return result.toString();
        }
        // 不包含下划线，直接首字母大写
        else {
            return Character.toUpperCase(input.charAt(0)) +
                    (input.length() > 1 ? input.substring(1).toLowerCase() : "");
        }
    }


}
